import React, { Component } from 'react';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      hasError: false,
      error: null,
      errorInfo: null
    };
  }

  static getDerivedStateFromError(error) {
    // 更新状态，下次渲染时显示错误UI
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    // 记录错误信息
    this.setState({
      error: error,
      errorInfo: errorInfo
    });
    console.error("错误边界捕获到错误:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 自定义错误显示
      return (
        <div style={{
          padding: '20px',
          margin: '20px auto',
          maxWidth: '600px',
          backgroundColor: '#fff',
          borderRadius: '8px',
          boxShadow: '0 2px 10px rgba(0,0,0,0.1)',
          textAlign: 'center'
        }}>
          <h2 style={{color: '#e74c3c'}}>应用出现错误</h2>
          <p>很抱歉，应用遇到了问题。请尝试以下解决方案：</p>
          <ul style={{textAlign: 'left', lineHeight: '1.6', margin: '20px 0'}}>
            <li>使用Chrome、Firefox或Safari等现代浏览器</li>
            <li>使用<strong>localhost</strong>或<strong>HTTPS</strong>访问（麦克风访问需要安全上下文）</li>
            <li>确保已授予麦克风访问权限</li>
            <li>刷新页面重试</li>
          </ul>
          <div style={{margin: '20px 0', padding: '10px', backgroundColor: '#f8f9fa', borderRadius: '4px', textAlign: 'left', overflow: 'auto'}}>
            <p style={{fontWeight: 'bold', color: '#e74c3c'}}>{this.state.error && this.state.error.toString()}</p>
            {this.state.errorInfo && (
              <details style={{whiteSpace: 'pre-wrap', marginTop: '10px', fontSize: '12px', color: '#666'}}>
                <summary style={{cursor: 'pointer', color: '#3498db'}}>查看详细错误信息</summary>
                {this.state.errorInfo.componentStack}
              </details>
            )}
          </div>
          <button 
            onClick={() => window.location.reload()} 
            style={{
              padding: '8px 16px',
              backgroundColor: '#3498db',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '16px'
            }}
          >
            刷新页面
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary; 